function forMatNum(num){
	return num<10?'0'+num:num+'';
}

function initDays(year,month){
	let totalDays=new Date(year,month,0).getDate();
	let dates=[];
	for(let d=1;d<=totalDays;d++){
		dates.push(forMatNum(d));
	};
	return dates;
}
function initPicker(start,end,mode="date",step) {
	let aToday=new Date();
	let tYear=aToday.getFullYear().toString();
	let tMonth=forMatNum(aToday.getMonth()+1).toString();
	let tDay=forMatNum(aToday.getDate()).toString();
	let tHours=forMatNum(aToday.getHours()).toString();
	let tMinutes=forMatNum(aToday.getMinutes()).toString();
	let tSeconds=forMatNum(aToday.getSeconds()).toString();
	let initstartDate=new Date(start);
	let endDate=new Date(end);
	if(start>end){
		initstartDate=new Date(end);
		endDate=new Date(start);
	};
	let startYear=initstartDate.getFullYear();
	let startMonth=initstartDate.getMonth();
	let endYear=endDate.getFullYear();
	let years=[],months=[],days=[],hours=[],minutes=[],seconds=[],defaultVal=[];
	let totalDays=new Date(startYear,startMonth,0).getDate();
	for(let s=startYear;s<=endYear;s++){
		years.push(s+'');
	};
	for(let m=1;m<=12;m++){
		months.push(forMatNum(m));
	};
	for(let d=1;d<=totalDays;d++){
		days.push(forMatNum(d));
	}
	for(let h=0;h<24;h++){
		hours.push(forMatNum(h));
	}
	for(let m=0;m<60;m+=step*1){
		minutes.push(forMatNum(m));
	}
	for(let s=0;s<60;s++){
		seconds.push(forMatNum(s));
	}
	switch(mode){
		case "date":
			defaultVal=[years.indexOf(tYear),months.indexOf(tMonth),days.indexOf(tDay)];
			return {years,months,days,defaultVal}
			break;
		case "yearMonth":
			defaultVal=[years.indexOf(tYear),months.indexOf(tMonth)];
			return {years,months,defaultVal}
			break;
		case "dateTime":
			defaultVal=[years.indexOf(tYear),months.indexOf(tMonth),days.indexOf(tDay),hours.indexOf(tHours),minutes.indexOf(tMinutes),seconds.indexOf(tSeconds)];
			return {years,months,days,hours,minutes,seconds,defaultVal}
			break;
		case "time":
			defaultVal=[hours.indexOf(tHours),minutes.indexOf(tMinutes),seconds.indexOf(tSeconds)];
			return {hours,minutes,seconds,defaultVal}
			break;			
	}
}

// 参数： url:请求地址  param：请求参数  way：请求方式 callBack：回调函数
function urlRequest(url, param, way, callBack) {
	let baseParam = {
		deviceId: "",
		os:"ios",
		ip:'192.168.1.35',
		versionName:"1.1.0",
		version:"",
		pageNum: "",
		pageSize: "",
		appName:"hfp",
		userId:"123"
	}
	let token = "";
	uni.getStorage({
		key: 'token',
		success: function(res) {
			token = res.data 
		}
	});
	uni.request({
		url: url, //仅为示例，并非真实接口地址。
		data: JSON.stringify(Object.assign(param,baseParam)),
		header: {
			'Token': token,
			'Accept': 'application/json',
			'Content-Type': 'application/json', //自定义请求头信息
		},
		method: way,
		success: (res) => {

		}
	});
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
// 数组对象根据指定市区排序
function objSort(arr, param, str){
	let newArr = [];
	try {
		arr.forEach(function (curItem, i) {
			if (item[param] == undefined) {
				console.log('地址信息中没有district字段');
				throw Error();
			}else{
				console.log(item);
				if(item[param].indexOf(str) > -1){
					newArr.unshift(item);
				}else{
					newArr.push(item);
				}
			}
		})
	} catch (e) {
		console.log('e', e);
	}
	return newArr;
}

function myTime(date){
     var arr=date.split("T");
     var d=arr[0];
   var darr = d.split('-');

   var t=arr[1];
   var tarr = t.split('.000');
   var marr = tarr[0].split(':');

   var dd = parseInt(darr[0])+"/"+parseInt(darr[1])+"/"+parseInt(darr[2])+" "+parseInt(marr[0])+":"+parseInt(marr[1])+":"+parseInt(marr[2]);
 return dd;
}

 // 数字补0操作
function  addZero(num) {
    return num < 10 ? '0' + num : num;
} 
/**
 * json时间格式化
 * @param {Object} date
 * @param {Object} fmt
 */
function formatDate(date, fmt) {
	/* if (!date) date = new date();
	if (!fmt) fmt = "yyyy-MM-dd"; */
	date = date == undefined ? new Date() : date;
	date = typeof date == 'number' ? new Date(date) : date;
	fmt = fmt || 'yyyy-MM-dd';
	var arr = date.split("T");
	var d = arr[0];
	var darr = d.split('-');
	var t = arr[1];
	var tarr = t.split('.000');
	var marr = tarr[0].split(':');
	var dd = parseInt(darr[0]) + "/" + parseInt(darr[1]) + "/" + parseInt(darr[2]) + " " + parseInt(marr[0]) + ":" + parseInt(marr[1]) + ":" + parseInt(marr[2]);
	var time = new Date(Date.parse(dd));
	time.setTime(time.setHours(time.getHours() + 8));
	var o = {
		"M+" : time.getMonth()+1, //月份           
		"d+" : time.getDate(), //日           
		"h+" : time.getHours()%12 == 0 ? 12 : time.getHours()%12, //小时           
		"H+" : time.getHours(), //小时           
		"m+" : time.getMinutes(), //分           
		"s+" : time.getSeconds(), //秒           
		"q+" : Math.floor((time.getMonth()+3)/3), //季度           
		"S" : time.getMilliseconds() //毫秒     
	};
	var week = {"0": "/u65e5", "1": "/u4e00", "2": "/u4e8c", "3": "/u4e09", "4": "/u56db", "5": "/u4e94", "6": "/u516d"};    
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
	if(/(E+)/.test(fmt)){fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);}
	for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

/**
 * js时间格式化
 * @param {Object} fmt
 * @param {Object} date
 */
function dateFtt(date,fmt) 
{ //author: meizz 
	 var o = { 
	 "M+" : date.getMonth()+1,     //月份 
	 "d+" : date.getDate(),     //日 
	 "HH+" : date.getHours(),     //小时 
	 "m+" : date.getMinutes(),     //分 
	 "s+" : date.getSeconds(),     //秒 
	 "q+" : Math.floor((date.getMonth()+3)/3), //季度 
	 "S" : date.getMilliseconds()    //毫秒 
	 }; 
	 if(/(y+)/.test(fmt)) 
	 fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); 
	 for(var k in o) 
	 if(new RegExp("("+ k +")").test(fmt)) 
	 fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
	 return fmt; 
}

/**
 * @description 根据当前时间预估几点送达
 * @param {Object} time 经历的好秒数
 * @param {Object} fmt  格式化的正则
 */
function estimatedTime(time, fmt) {
	time = typeof time == 'number' ? time : Number(time);
	fmt = fmt || 'HH:mm';
	console.log('time', time);
	let date = new Date().getFullYear() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getDate() + ' ' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds();
	console.log('new Date(date).getTime()', new Date(date).getTime());
	let times = new Date(date).getTime() + time * 1000 + (30*60*1000);//额外增加30分钟
	let newDate = new Date(times);
	var o = {
		"M+" : newDate.getMonth()+1, //月份
		"d+" : newDate.getDate(), //日           
		"h+" : newDate.getHours()%12 == 0 ? 12 : newDate.getHours()%12, //小时           
		"H+" : newDate.getHours(), //小时           
		"m+" : newDate.getMinutes(), //分           
		"s+" : newDate.getSeconds(), //秒           
		"q+" : Math.floor((newDate.getMonth()+3)/3), //季度           
		"S" : newDate.getMilliseconds() //毫秒   
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (newDate.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

/**
 * @param {Object} beginTime	开始时间
 * @param {Object} endTime		结束时间
 * @param {Object} nowTime		当前时间
 */
function timeRange(beginTime, endTime, nowTime) {
    var strb = beginTime.split(":");
    if (strb.length != 3) {
		console.log(1);
        return false;
    }

    var stre = endTime.split(":");
    if (stre.length != 3) {
		console.log(2);
        return false;
    }

    var strn = nowTime ? nowTime.split(":") : (new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds()).split(':');
    if (strn.length != 3) {
		console.log(3);
        return false;
    }
    var b = new Date();
    var e = new Date();
    var n = new Date();

    b.setHours(strb[0]);
    b.setMinutes(strb[1]);
    e.setHours(stre[0]);
    e.setMinutes(stre[1]);
    n.setHours(strn[0]);
    n.setMinutes(strn[1]);

    if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
		let message = {
        	status: true,
        	msg: '随时配送'
        };
        return message;
    } else {
        console.log("当前时间是：" + n.getHours() + ":" + n.getMinutes() + "，不在该时间范围内！");
		let message = {
			status: false,
			msg: beginTime.slice(0, 5) + '后配送'
		};
        return message;
    }
}

/**
 * @description 根据属性值删除数组对象
 * @param {Object} arr		数组对象
 * @param {Object} attr		要删除的数组对象的key
 * @param {Object} value	要删除的数组对象的value
 */
function removeByValue(arr,attr,value) {//数组，属性，属性值
	for(var j=0;j<arr.length;j++){
		if(arr[j][attr] == value){
			 arr.splice(j,1);
			 break;
		 }
	}
	return arr;
}

export default{
	initDays,
	initPicker,
	formatLocation,
	urlRequest: function(url, param, way) {
		return urlRequest(url, param, way);
	},
	objSort,
	formatDate,
	estimatedTime,
	removeByValue,
	dateFtt,
	timeRange
}